<template>
  <div class="flex h-screen overflow-hidden">
    <!-- 模态对话框组件 -->
    <Transition name="modal">
      <div v-if="modal.show" class="modal-backdrop" @click.self="closeModal">
        <div class="modal-content">
          <div class="p-4 border-b">
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-medium" :class="getModalHeaderClass">{{ modal.title }}</h3>
              <button @click="closeModal" class="text-gray-400 hover:text-gray-500">
                <i class="bi bi-x-lg"></i>
              </button>
            </div>
          </div>
          <div class="p-4">
            <p>{{ modal.message }}</p>
            <div v-if="modal.showForm" class="mt-4 space-y-4">
              <div>
                <label for="productName" class="block text-sm font-medium text-gray-700 mb-1">
                  商品名称
                </label>
                <input 
                  type="text" 
                  id="productName" 
                  v-model="modal.formData.name" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="请输入商品名称"
                />
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label for="productPrice" class="block text-sm font-medium text-gray-700 mb-1">
                    销售价格
                  </label>
                  <input 
                    type="number" 
                    id="productPrice" 
                    v-model="modal.formData.price" 
                    class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                  />
                </div>
                <div>
                  <label for="productOriginalPrice" class="block text-sm font-medium text-gray-700 mb-1">
                    原价
                  </label>
                  <input 
                    type="number" 
                    id="productOriginalPrice" 
                    v-model="modal.formData.originalPrice" 
                    class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                  />
                </div>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label for="productStock" class="block text-sm font-medium text-gray-700 mb-1">
                    库存数量
                  </label>
                  <input 
                    type="number" 
                    id="productStock" 
                    v-model="modal.formData.stock" 
                    class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    placeholder="0"
                    min="0"
                  />
                </div>
                <div>
                  <label for="productCategory" class="block text-sm font-medium text-gray-700 mb-1">
                    商品分类
                  </label>
                  <div class="relative">
                    <select 
                      id="productCategory" 
                      v-model="modal.formData.categoryId" 
                      class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                      :disabled="productStore.categoriesLoading"
                    >
                      <option v-if="productStore.categoriesLoading" value="">加载中...</option>
                      <option v-else-if="productStore.categories.length === 0" value="">暂无分类可选</option>
                      <template v-else>
                        <option 
                          v-for="category in organizedCategories.slice(1)" 
                          :key="category.id" 
                          :value="category.id"
                          :style="category.level === 1 ? { paddingLeft: '20px' } : {}"
                          :class="{ 'font-semibold': category.isParent }"
                        >
                          {{ category.level === 1 ? '　　' + category.name : category.name }}
                        </option>
                      </template>
                    </select>
                    <div v-if="productStore.categoriesLoading" class="absolute right-3 top-1/2 transform -translate-y-1/2">
                      <div class="animate-spin h-4 w-4 border-b-2 border-indigo-500 rounded-full"></div>
                    </div>
                  </div>
                  <div v-if="productStore.categoriesLoading" class="mt-1 text-xs text-red-500">
                    <i class="bi bi-exclamation-circle mr-1"></i>
                    <span>{{ productStore.categoriesError }}</span>
                    <button 
                      @click="productStore.fetchCategories()" 
                      class="text-indigo-500 underline ml-2 focus:outline-none"
                    >
                      重试
                    </button>
                  </div>
                </div>
              </div>
              <div>
                <label for="productImages" class="block text-sm font-medium text-gray-700 mb-1">
                  商品图片
                </label>
                <div class="mt-1 flex items-center">
                  <!-- 显示已上传的图片预览 -->
                  <div v-if="modal.formData.imageFiles && modal.formData.imageFiles.length > 0" class="flex flex-wrap gap-2">
                    <div v-for="(file, index) in modal.formData.imageFiles" :key="index" class="relative group">
                      <img :src="previewImages[index]" class="h-20 w-20 object-cover rounded-md border border-gray-300" alt="商品图片预览" />
                      <button 
                        @click="removeImage(index)" 
                        class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                        title="删除图片"
                      >
                        <i class="bi bi-x-lg text-xs"></i>
                      </button>
                    </div>
                  </div>
                  
                  <!-- 图片上传按钮 -->
                  <label for="productImages" class="ml-2 cursor-pointer inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none">
                    <i class="bi bi-upload mr-2"></i>
                    {{ modal.formData.imageFiles && modal.formData.imageFiles.length > 0 ? '添加更多图片' : '上传图片' }}
                    <input 
                      type="file" 
                      id="productImages" 
                      @change="handleImageUpload" 
                      accept="image/*" 
                      multiple
                      class="hidden"
                    />
                  </label>
                </div>
                <p class="mt-1 text-xs text-gray-500">支持JPG、PNG等格式，每张图片不超过2MB</p>
              </div>
              <div>
                <label for="productDescription" class="block text-sm font-medium text-gray-700 mb-1">
                  商品描述 <span class="text-red-500">*</span>
                </label>
                <textarea 
                  id="productDescription" 
                  v-model="modal.formData.description" 
                  rows="3"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="请输入商品简要描述（必填）"
                ></textarea>
              </div>
              <div>
                <label for="productDetail" class="block text-sm font-medium text-gray-700 mb-1">
                  商品详情（选填）
                </label>
                <textarea 
                  id="productDetail" 
                  v-model="modal.formData.detail" 
                  rows="5"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="请输入商品详情描述，支持简单HTML格式"
                ></textarea>
              </div>
              <div>
                <label for="productTags" class="block text-sm font-medium text-gray-700 mb-1">
                  商品标签
                </label>
                <div class="flex flex-wrap gap-2 mb-2">
                  <span 
                    v-for="(tag, index) in modal.formData.tags" 
                    :key="index"
                    class="inline-flex items-center px-2 py-1 rounded-md text-sm font-medium bg-indigo-100 text-indigo-800"
                  >
                    {{ tag }}
                    <button 
                      @click="removeTag(index)" 
                      class="ml-1 text-indigo-600 hover:text-indigo-900"
                      title="删除标签"
                    >
                      <i class="bi bi-x"></i>
                    </button>
                  </span>
                </div>
                <div class="flex">
                  <input 
                    type="text" 
                    id="productTags" 
                    v-model="tagInput" 
                    @keypress.enter="addTag"
                    class="flex-1 px-3 py-2 border border-gray-300 rounded-l-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    placeholder="输入标签后按回车添加"
                  />
                  <button 
                    @click="addTag" 
                    class="px-4 py-2 border border-transparent rounded-r-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  >
                    添加
                  </button>
                </div>
              </div>
              <div class="flex items-center">
                <input 
                  type="checkbox" 
                  id="productStatus" 
                  v-model="modal.formData.status" 
                  class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                  true-value="1"
                  false-value="0"
                />
                <label for="productStatus" class="ml-2 block text-sm text-gray-700">
                  上架商品
                </label>
              </div>
            </div>
          </div>
          <div class="px-4 py-3 bg-gray-50 flex justify-end space-x-2 rounded-b-lg">
            <button v-if="modal.showCancelButton" @click="closeModal" class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
              {{ modal.cancelButtonText }}
            </button>
            <button @click="confirmModal" :class="getModalConfirmButtonClass" class="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white">
              {{ modal.confirmButtonText }}
            </button>
          </div>
        </div>
      </div>
    </Transition>
    
    <!-- 侧边栏 -->
    <div :class="['bg-gray-900 text-white w-64 flex flex-col transition-all duration-300 ease-in-out', isSidebarOpen ? 'translate-x-0' : '-translate-x-64 md:translate-x-0']">
      <!-- 侧边栏头部 -->
      <div class="flex items-center justify-between px-4 py-3 bg-gray-800">
        <div class="flex items-center">
          <img src="https://via.placeholder.com/40" alt="Logo" class="h-8 w-8 rounded-full">
          <span class="ml-2 text-xl font-semibold">商城管理系统</span>
        </div>
        <button @click="toggleSidebar" class="md:hidden text-gray-300 hover:text-white">
          <i class="bi bi-x-lg"></i>
        </button>
      </div>
      
      <!-- 侧边栏菜单 -->
      <nav class="flex-1 overflow-y-auto py-4">
        <ul class="space-y-1">
          <li>
            <router-link to="/dashboard" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-speedometer2 mr-3"></i>
              <span>控制台</span>
            </router-link>
          </li>
          <li>
            <router-link to="/products" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white" active-class="bg-gray-700 text-white">
              <i class="bi bi-box-seam mr-3"></i>
              <span>商品管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/categories" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-tags mr-3"></i>
              <span>分类管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/orders" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-cart3 mr-3"></i>
              <span>订单管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/inventory" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-clipboard-data mr-3"></i>
              <span>库存管理</span>
            </router-link>
          </li>
          <li>
            <router-link to="/statistics" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-graph-up mr-3"></i>
              <span>数据统计</span>
            </router-link>
          </li>
          <li>
            <router-link to="/settings" class="flex items-center px-4 py-2 text-gray-300 hover:bg-gray-700 hover:text-white">
              <i class="bi bi-gear mr-3"></i>
              <span>系统设置</span>
            </router-link>
          </li>
        </ul>
      </nav>
      
      <!-- 侧边栏底部 -->
      <div class="p-4 bg-gray-800">
        <div class="flex items-center">
          <img src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="用户头像" class="h-8 w-8 rounded-full">
          <div class="ml-3">
            <p class="text-sm font-medium text-white">管理员</p>
            <p class="text-xs text-gray-300">admin@example.com</p>
          </div>
        </div>
        <div class="mt-3">
          <button @click="logout" class="flex items-center justify-center px-4 py-2 text-sm text-white bg-gray-700 rounded-md hover:bg-gray-600">
            <i class="bi bi-box-arrow-left mr-2"></i>
            退出登录
          </button>
        </div>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部导航栏 -->
      <header class="bg-white border-b border-gray-200 shadow-sm">
        <div class="flex items-center justify-between px-4 py-3">
          <div class="flex items-center">
            <button @click="toggleSidebar" class="text-gray-500 focus:outline-none md:hidden">
              <i class="bi bi-list text-xl"></i>
            </button>
            <h1 class="ml-4 text-lg font-semibold text-gray-700">商品管理</h1>
          </div>
          <div class="flex items-center space-x-4">
            <button class="text-gray-500 hover:text-gray-600 focus:outline-none">
              <i class="bi bi-bell"></i>
            </button>
            <button class="flex items-center text-gray-500 hover:text-gray-600 focus:outline-none">
              <img src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="用户头像" class="h-8 w-8 rounded-full">
              <span class="ml-2 text-sm font-medium">管理员</span>
              <i class="bi bi-chevron-down ml-1"></i>
            </button>
          </div>
        </div>
      </header>
      
      <!-- 页面内容 -->
      <main class="flex-1 overflow-y-auto p-4">
        <!-- 操作栏 -->
        <div class="bg-white rounded-lg shadow p-4 mb-6">
          <div class="flex flex-col md:flex-row md:items-center md:justify-between space-y-3 md:space-y-0">
            <div class="flex flex-col md:flex-row md:items-center space-y-3 md:space-y-0 md:space-x-4">
              <!-- 搜索框 -->
              <div class="relative">
                <i class="bi bi-search text-gray-400 search-icon"></i>
                <input 
                  v-model="productStore.searchKeyword" 
                  type="text" 
                  class="block w-full search-input pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" 
                  placeholder="输入关键词搜索商品"
                >
                <div v-if="productStore.searchKeyword" class="absolute right-2 top-1/2 transform -translate-y-1/2">
                  <button 
                    @click="clearSearch" 
                    class="text-gray-400 hover:text-gray-500 p-1"
                    title="清除搜索"
                  >
                    <i class="bi bi-x"></i>
                  </button>
                </div>
                <div v-if="productStore.searchLoading" class="absolute right-10 top-1/2 transform -translate-y-1/2">
                  <div class="animate-spin h-4 w-4 border-b-2 border-indigo-500 rounded-full"></div>
                </div>
              </div>
              
              <!-- 分类筛选 -->
              <div class="relative w-full md:w-40">
                <select 
                  v-model="productStore.categoryFilter" 
                  class="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                  :disabled="productStore.categoriesLoading"
                >
                  <option 
                    v-for="category in organizedCategories" 
                    :key="category.id" 
                    :value="category.id"
                    :style="category.level === 1 ? { paddingLeft: '20px' } : {}"
                    :class="{ 'font-semibold': category.isParent }"
                  >
                    {{ category.level === 1 ? '　　' + category.name : category.name }}
                  </option>
                </select>
                <div v-if="productStore.categoriesLoading" class="absolute right-3 top-1/2 transform -translate-y-1/2">
                  <div class="animate-spin h-4 w-4 border-b-2 border-indigo-500 rounded-full"></div>
                </div>
                <div v-if="productStore.categoriesError" class="absolute mt-1 text-xs text-red-500">
                  <i class="bi bi-exclamation-circle mr-1"></i>
                  <span>加载分类失败</span>
                </div>
              </div>
              
              <!-- 状态筛选 -->
              <select v-model="productStore.statusFilter" class="block w-full md:w-40 py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
                <option value="">全部状态</option>
                <option value="1">上架中</option>
                <option value="0">已下架</option>
              </select>
            </div>
            
            <div class="flex space-x-2">
              <!-- 批量操作按钮 -->
              <div v-if="productStore.selectedProducts.length > 0" class="flex space-x-2">
                <button @click="batchUpdateStatus(1)" class="flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                  <i class="bi bi-check-circle mr-2"></i>
                  批量上架
                </button>
                <button @click="batchUpdateStatus(0)" class="flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gray-600 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
                  <i class="bi bi-x-circle mr-2"></i>
                  批量下架
                </button>
                <button @click="batchDelete" class="flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                  <i class="bi bi-trash mr-2"></i>
                  批量删除
                </button>
              </div>
              
              <!-- 添加商品按钮 -->
              <button @click="openAddModal" class="flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                <i class="bi bi-plus-lg mr-2"></i>
                添加商品
              </button>
              
              <!-- 刷新按钮 -->
              <button @click="refreshProducts" class="flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ml-2">
                <i class="bi bi-arrow-clockwise mr-2"></i>
                刷新
              </button>
            </div>
          </div>
        </div>
        
        <!-- 商品列表 -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
          <!-- 添加搜索状态提示 -->
          <div v-if="productStore.searchKeyword && !productStore.searchLoading && !productStore.searchError" class="bg-blue-50 px-4 py-2 border-b border-blue-100">
            <div class="flex items-center justify-between">
              <div class="flex items-center text-sm text-blue-700">
                <i class="bi bi-info-circle mr-2"></i>
                正在显示搜索"{{ productStore.searchKeyword }}"的结果：共 {{ productStore.pagination.total }} 条记录
              </div>
              <button 
                @click="clearSearch" 
                class="text-blue-600 hover:text-blue-800 text-sm font-medium"
              >
                <i class="bi bi-x-circle mr-1"></i>
                清除搜索
              </button>
            </div>
          </div>
          
          <!-- 搜索错误提示 -->
          <div v-if="productStore.searchError" class="bg-red-50 px-4 py-2 border-b border-red-100">
            <div class="flex items-center justify-between">
              <div class="flex items-center text-sm text-red-700">
                <i class="bi bi-exclamation-circle mr-2"></i>
                {{ productStore.searchError }}
              </div>
              <button 
                @click="clearSearch" 
                class="text-red-600 hover:text-red-800 text-sm font-medium"
              >
                <i class="bi bi-x-circle mr-1"></i>
                清除搜索
              </button>
            </div>
          </div>
          
          <!-- 添加加载状态提示 -->
          <div v-if="productStore.loading || productStore.searchLoading" class="flex justify-center items-center p-10">
            <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600"></div>
            <span class="ml-3 text-gray-500">{{ productStore.isSearchMode ? '正在搜索...' : '正在加载数据...' }}</span>
          </div>
          
          <!-- 错误提示 -->
          <div v-else-if="productStore.error" class="p-10 text-center">
            <div class="text-red-500">
              <i class="bi bi-exclamation-triangle text-3xl"></i>
              <p class="mt-2">{{ productStore.error }}</p>
              <button 
                @click="productStore.fetchProducts()" 
                class="mt-4 px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                重试
              </button>
            </div>
          </div>
          
          <div v-else class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <div class="flex items-center">
                      <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                    </div>
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品信息</th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <div class="flex items-center cursor-pointer" @click="toggleSort('price')">
                      价格
                      <span class="ml-1">
                        <i 
                          v-if="productStore.sortInfo.sort === 'price'" 
                          :class="[
                            'bi', 
                            productStore.sortInfo.order === 'asc' ? 'bi-arrow-up' : 'bi-arrow-down'
                          ]"
                        ></i>
                        <i v-else class="bi bi-arrow-down text-gray-300"></i>
                      </span>
                    </div>
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <div class="flex items-center cursor-pointer" @click="toggleSort('stock')">
                      库存
                      <span class="ml-1">
                        <i 
                          v-if="productStore.sortInfo.sort === 'stock'" 
                          :class="[
                            'bi', 
                            productStore.sortInfo.order === 'asc' ? 'bi-arrow-up' : 'bi-arrow-down'
                          ]"
                        ></i>
                        <i v-else class="bi bi-arrow-down text-gray-300"></i>
                      </span>
                    </div>
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                  <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="product in productStore.filteredProducts" :key="product.id">
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                      <input type="checkbox" v-model="productStore.selectedProducts" :value="product.id" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                    </div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                      <div class="flex-shrink-0 h-10 w-10">
                        <img class="h-10 w-10 rounded-sm object-cover" :src="product.image" alt="">
                      </div>
                      <div class="ml-4">
                        <div class="text-sm font-medium text-gray-900">{{ product.name }}</div>
                        <div class="text-xs text-gray-500">ID: {{ product.id }}</div>
                      </div>
                    </div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">¥{{ product.price }}</div>
                    <div class="text-xs text-gray-500" v-if="product.originalPrice">原价: ¥{{ product.originalPrice }}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">{{ product.stock }}</div>
                    <div class="text-xs text-gray-500">销量: {{ product.sales }}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">{{ productStore.getCategoryName(product.categoryId) }}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span :class="[
                      'px-2 inline-flex text-xs leading-5 font-semibold rounded-full',
                      product.status === 1 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                    ]">
                      {{ product.status === 1 ? '上架中' : '已下架' }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button @click="editProduct(product)" class="text-indigo-600 hover:text-indigo-900 mr-3">编辑</button>
                    <button @click="toggleStatus(product)" :class="[product.status === 1 ? 'text-gray-600 hover:text-gray-900' : 'text-green-600 hover:text-green-900']">
                      {{ product.status === 1 ? '下架' : '上架' }}
                    </button>
                    <button @click="deleteProduct(product)" class="text-red-600 hover:text-red-900 ml-3">
                      删除
                    </button>
                  </td>
                </tr>
                
                <!-- 无数据提示 -->
                <tr v-if="productStore.filteredProducts.length === 0">
                  <td colspan="7" class="px-6 py-10 text-center text-sm text-gray-500">
                    <div class="flex flex-col items-center">
                      <i class="bi bi-inbox text-4xl text-gray-300 mb-3"></i>
                      <span v-if="productStore.isSearchMode">找不到与"{{ productStore.searchKeyword }}"相关的商品</span>
                      <span v-else>暂无符合条件的商品</span>
                      <button 
                        v-if="productStore.isSearchMode"
                        @click="clearSearch" 
                        class="mt-4 px-4 py-2 text-sm text-indigo-600 border border-indigo-300 rounded-md hover:bg-indigo-50"
                      >
                        清除搜索条件
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 分页 -->
          <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="flex-1 flex justify-between sm:hidden">
              <button 
                :disabled="productStore.pagination.page <= 1" 
                @click="goToPage(productStore.pagination.page - 1)" 
                :class="[
                  'relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700',
                  productStore.pagination.page <= 1 ? 'bg-gray-100 cursor-not-allowed' : 'bg-white hover:bg-gray-50'
                ]"
              >
                上一页
              </button>
              <button 
                :disabled="productStore.pagination.page >= productStore.pagination.pages" 
                @click="goToPage(productStore.pagination.page + 1)" 
                :class="[
                  'ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700',
                  productStore.pagination.page >= productStore.pagination.pages ? 'bg-gray-100 cursor-not-allowed' : 'bg-white hover:bg-gray-50'
                ]"
              >
                下一页
              </button>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
              <div>
                <p class="text-sm text-gray-700">
                  显示 
                  <span class="font-medium">{{ ((productStore.pagination.page - 1) * productStore.pagination.limit) + 1 }}</span> 
                  到 
                  <span class="font-medium">
                    {{ Math.min(productStore.pagination.page * productStore.pagination.limit, productStore.pagination.total) }}
                  </span> 
                  条，共 
                  <span class="font-medium">{{ productStore.pagination.total }}</span> 条记录
                </p>
              </div>
              <div>
                <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                  <!-- 上一页按钮 -->
                  <button 
                    :disabled="productStore.pagination.page <= 1" 
                    @click="goToPage(productStore.pagination.page - 1)" 
                    :class="[
                      'relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500',
                      productStore.pagination.page <= 1 ? 'cursor-not-allowed' : 'hover:bg-gray-50'
                    ]"
                  >
                    <span class="sr-only">上一页</span>
                    <i class="bi bi-chevron-left"></i>
                  </button>
                  
                  <!-- 页码 -->
                  <template v-for="pageNum in paginationNumbers">
                    <span
                      v-if="pageNum === '...'"
                      :key="'ellipsis-' + pageNum"
                      class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700"
                    >
                      ...
                    </span>
                    <button
                      v-else
                      :key="pageNum"
                      @click="goToPage(pageNum)"
                      :class="[
                        'relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium',
                        productStore.pagination.page === pageNum
                          ? 'bg-indigo-50 text-indigo-600'
                          : 'bg-white text-gray-700 hover:bg-gray-50'
                      ]"
                    >
                      {{ pageNum }}
                    </button>
                  </template>
                  
                  <!-- 下一页按钮 -->
                  <button 
                    :disabled="productStore.pagination.page >= productStore.pagination.pages" 
                    @click="goToPage(productStore.pagination.page + 1)" 
                    :class="[
                      'relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500',
                      productStore.pagination.page >= productStore.pagination.pages ? 'cursor-not-allowed' : 'hover:bg-gray-50'
                    ]"
                  >
                    <span class="sr-only">下一页</span>
                    <i class="bi bi-chevron-right"></i>
                  </button>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </main>
      
      <!-- 底部 -->
      <footer class="bg-white border-t border-gray-200 px-4 py-3">
        <div class="text-center text-sm text-gray-500">
          © {{ new Date().getFullYear() }} 微信商城后台管理系统 版权所有
        </div>
      </footer>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useProductsStore } from '@/stores/products';
import { useUserStore } from '@/stores/user';
import { getImageUrl } from '@/utils/imageHelper.js';

export default {
  name: 'ProductsView',
  setup() {
    const router = useRouter();
    const productStore = useProductsStore();
    const userStore = useUserStore();

    // 顶级分类计算属性
    const topLevelCategories = computed(() => {
      return productStore.categories.filter(category => 
        category.parentId === null || category.parentId === undefined
      );
    });

    // 子分类计算属性
    const subCategories = computed(() => {
      return productStore.categories.filter(category => 
        category.parentId !== null && category.parentId !== undefined
      ).sort((a, b) => {
        // 按父分类名称和自身排序权重排序
        const parentA = productStore.categories.find(c => c.id === a.parentId);
        const parentB = productStore.categories.find(c => c.id === b.parentId);
        
        if (parentA && parentB) {
          if (parentA.name !== parentB.name) {
            return parentA.name.localeCompare(parentB.name);
          }
        }
        
        return a.sort - b.sort;
      });
    });

    // 获取父分类名称
    function getParentCategoryName(parentId) {
      const parent = productStore.categories.find(c => c.id === parentId);
      return parent ? parent.name : '';
    }
    
    // 获取特定父分类下的子分类
    function getChildCategories(parentId) {
      return productStore.categories.filter(
        category => category.parentId === parentId
      ).sort((a, b) => a.sort - b.sort);
    }
    
    // 按层次组织的所有分类
    const organizedCategories = computed(() => {
      const result = [];
      
      // 添加全部分类选项
      result.push({ id: '', name: '全部分类', isParent: false, level: 0 });
      
      // 添加父分类及其子分类
      topLevelCategories.value.forEach(parent => {
        // 添加父分类
        result.push({ ...parent, isParent: true, level: 0 });
        
        // 添加该父分类下的所有子分类
        const children = getChildCategories(parent.id);
        children.forEach(child => {
          result.push({ ...child, isParent: false, level: 1 });
        });
      });
      
      return result;
    });

    // 侧边栏状态
    const isSidebarOpen = ref(false);
    
    // 全选状态
    const selectAll = ref(false);
    
    // 模态对话框状态
    const modal = reactive({
      show: false,
      title: '',
      message: '',
      type: 'info', // info, success, warning, danger
      showCancelButton: false,
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      showForm: false,
      formData: {
        id: '',
        name: '',
        price: '',
        originalPrice: '',
        stock: 0,
        categoryId: '',
        image: '',
        description: '',
        status: 1
      },
      callback: null
    });
    
    // 模态对话框样式计算属性
    const getModalHeaderClass = computed(() => {
      switch (modal.type) {
        case 'success': return 'text-green-600';
        case 'warning': return 'text-yellow-600';
        case 'danger': return 'text-red-600';
        default: return 'text-gray-900';
      }
    });
    
    const getModalConfirmButtonClass = computed(() => {
      switch (modal.type) {
        case 'success': return 'bg-green-600 hover:bg-green-700';
        case 'warning': return 'bg-yellow-600 hover:bg-yellow-700';
        case 'danger': return 'bg-red-600 hover:bg-red-700';
        default: return 'bg-indigo-600 hover:bg-indigo-700';
      }
    });
    
    // 监听选中商品变化，更新全选状态
    watch(() => productStore.selectedProducts, (newVal) => {
      selectAll.value = newVal.length > 0 && newVal.length === productStore.filteredProducts.length;
    }, { deep: true });
    
    // 组件挂载后初始化数据
    onMounted(() => {
      // 确保每次组件挂载时都从API获取最新数据
      productStore.fetchCategories();
      productStore.fetchProducts();
    });
    
    // 页面激活时刷新数据
    watch(() => router.currentRoute.value, (newRoute) => {
      if (newRoute.path === '/products') {
        // 当路由切换到商品列表页时刷新数据
        productStore.fetchProducts();
      }
    }, { immediate: true });
    
    // 计算分页显示的页码
    const paginationNumbers = computed(() => {
      const currentPage = productStore.pagination.page;
      const totalPages = productStore.pagination.pages;
      
      if (totalPages <= 7) {
        // 如果总页数少于7，显示所有页码
        return Array.from({ length: totalPages }, (_, i) => i + 1);
      }
      
      // 否则显示当前页附近的页码和首尾页码
      const pages = [];
      
      // 显示第一页
      pages.push(1);
      
      // 当前页附近的页码
      if (currentPage > 3) {
        pages.push('...');
      }
      
      const start = Math.max(2, currentPage - 1);
      const end = Math.min(totalPages - 1, currentPage + 1);
      
      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
      
      if (currentPage < totalPages - 2) {
        pages.push('...');
      }
      
      // 显示最后一页
      if (totalPages > 1) {
        pages.push(totalPages);
      }
      
      return pages;
    });
    
    // 跳转到指定页码
    function goToPage(page) {
      if (page >= 1 && page <= productStore.pagination.pages) {
        productStore.setPage(page);
      }
    }
    
    // 切换排序方式
    function toggleSort(field) {
      if (productStore.sortInfo.sort === field) {
        // 切换排序方向
        const newOrder = productStore.sortInfo.order === 'asc' ? 'desc' : 'asc';
        productStore.setSort(field, newOrder);
      } else {
        // 切换排序字段，默认降序
        productStore.setSort(field, 'desc');
      }
    }
    
    // 切换全选
    function toggleSelectAll() {
      if (selectAll.value) {
        productStore.selectedProducts = productStore.filteredProducts.map(p => p.id);
      } else {
        productStore.selectedProducts = [];
      }
    }
    
    // 切换侧边栏
    function toggleSidebar() {
      isSidebarOpen.value = !isSidebarOpen.value;
    }
    
    // 批量更新商品状态
    async function batchUpdateStatus(status) {
      if (productStore.selectedProducts.length === 0) return;
      
      showModal({
        title: status === 1 ? '批量上架' : '批量下架',
        message: `确定要${status === 1 ? '上架' : '下架'}选中的 ${productStore.selectedProducts.length} 个商品吗？`,
        type: 'warning',
        showCancelButton: true,
        callback: async () => {
          // 显示处理中提示
          showModal({
            title: '处理中',
            message: `正在${status === 1 ? '上架' : '下架'}商品，请稍候...`,
            type: 'info'
          });
          
          let result;
          try {
            // 根据操作类型调用不同的批量API
            if (status === 1) {
              // 批量上架
              result = await productStore.batchPublishProducts();
            } else {
              // 批量下架
              result = await productStore.batchUnpublishProducts();
            }
            
            if (result && result.success) {
              // 显示成功提示
              showModal({
                title: '操作成功',
                message: result.message || `已${status === 1 ? '上架' : '下架'} ${productStore.selectedProducts.length} 个商品`,
                type: 'success'
              });
              
              // 清空选中
              productStore.selectedProducts = [];
            } else {
              // 显示错误提示
              showModal({
                title: '操作失败',
                message: result?.message || `批量${status === 1 ? '上架' : '下架'}商品失败`,
                type: 'danger'
              });
            }
          } catch (error) {
            console.error(`批量${status === 1 ? '上架' : '下架'}商品错误:`, error);
            // 显示错误提示
            showModal({
              title: '错误',
              message: error.message || `批量${status === 1 ? '上架' : '下架'}商品时发生错误`,
              type: 'danger'
            });
          }
        }
      });
    }
    
    // 批量删除商品
    function batchDelete() {
      if (productStore.selectedProducts.length === 0) return;
      
      showModal({
        title: '批量删除',
        message: `确定要删除选中的 ${productStore.selectedProducts.length} 个商品吗？此操作不可恢复！`,
        type: 'danger',
        showCancelButton: true,
        callback: () => {
          // 删除选中商品
          const result = productStore.batchDeleteProducts();
          
          if (result) {
            // 显示成功提示
            showModal({
              title: '操作成功',
              message: `已删除 ${productStore.selectedProducts.length} 个商品`,
              type: 'success'
            });
          }
        }
      });
    }
    
    // 切换商品状态
    async function toggleStatus(product) {
      // 显示进行中的提示
      showModal({
        title: '处理中',
        message: '正在更新商品状态，请稍候...',
        type: 'info'
      });
      
      console.log('商品信息:', product);
      
      // 检查ID格式
      if (!product.id && !product._id) {
        showModal({
          title: '错误',
          message: '无法获取商品ID，操作失败',
          type: 'danger'
        });
        return;
      }
      
      // 确保有可用的ID - 优先使用_id，这是MongoDB的原始ID格式
      const productId = product._id || product.id;
      console.log(`将使用ID: ${productId} 切换商品状态，当前状态: ${product.status}`);
      
      try {
        // 根据当前状态选择上架或下架API
        let result;
        if (product.status === 1) {
          // 当前是上架状态，需要下架
          console.log(`开始下架商品，ID: ${productId}`);
          console.log(`商品详情:`, JSON.stringify({
            id: productId,
            name: product.name,
            status: product.status,
            categoryId: product.categoryId
          }));
          
          result = await productStore.unpublishProductApi(productId);
        } else {
          // 当前是下架状态，需要上架
          console.log(`开始上架商品，ID: ${productId}`);
          console.log(`商品详情:`, JSON.stringify({
            id: productId,
            name: product.name,
            status: product.status,
            categoryId: product.categoryId
          }));
          
          result = await productStore.publishProductApi(productId);
        }
        
        console.log('API操作结果:', result);
        
        if (result && result.success) {
          // 更新本地状态
          const updatedStatus = product.status === 1 ? 0 : 1;
          
          // 显示成功提示
          showModal({
            title: '操作成功',
            message: result.message || `商品"${product.name}"状态已更新为${updatedStatus === 1 ? '上架' : '下架'}`,
            type: 'success'
          });
          
          // 刷新商品列表以获取最新数据
          await productStore.fetchProducts();
        } else {
          // 显示错误提示，带有更具体的错误信息
          const errorMsg = result?.message || '更新商品状态失败，请检查商品信息是否完整';
          console.error('操作失败:', errorMsg);
          
          showModal({
            title: '操作失败',
            message: errorMsg,
            type: 'danger'
          });
        }
      } catch (error) {
        console.error('更新商品状态时发生错误:', error);
        // 将所有错误信息记录下来，帮助排查问题
        if (error.response) {
          console.error('错误响应数据:', error.response.data);
          console.error('错误状态码:', error.response.status);
          console.error('错误头信息:', error.response.headers);
        }
        
        // 显示错误提示，带有更具体的错误信息
        showModal({
          title: '错误',
          message: error.message || '更新商品状态时发生错误，请稍后重试',
          type: 'danger'
        });
      }
    }
    
    // 删除单个商品
    function deleteProduct(product) {
      showModal({
        title: '删除商品',
        message: `确定要删除商品"${product.name}"吗？此操作不可恢复！`,
        type: 'danger',
        showCancelButton: true,
        callback: () => {
          const result = productStore.deleteProduct(product.id);
          
          if (result) {
            // 显示成功提示
            showModal({
              title: '成功',
              message: '商品已成功删除',
              type: 'success'
            });
          }
        }
      });
    }
    
    // 编辑商品
    function editProduct(product) {
      // 获取现有图片，转换为显示格式
      const existingImages = Array.isArray(product.images) ? 
        product.images : (product.image ? [product.image] : []);
      
      // 初始化图片预览
      previewImages.value = [...existingImages];
      
      showModal({
        title: '编辑商品',
        type: 'info',
        showForm: true,
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '保存',
        formData: {
          id: product.id,
          _id: product._id, // 保存原始MongoDB ID
          name: product.name,
          price: product.price,
          originalPrice: product.originalPrice || '',
          stock: product.stock,
          categoryId: product.categoryId,
          image: product.image,
          imageFiles: [], // 用于存储新上传的图片文件
          existingImages: existingImages, // 保存现有图片URL
          description: product.description || '',
          detail: product.detail || '',
          tags: product.tags || [],
          specs: product.specs || [],
          status: product.status.toString()
        },
        callback: async (formData) => {
          // 显示loading
          showModal({
            title: '处理中',
            message: '正在更新商品数据，请稍候...',
            type: 'info'
          });
          
          // 准备提交的数据
          const productData = {
            name: formData.name,
            description: formData.description,
            price: formData.price,
            originalPrice: formData.originalPrice || undefined,
            stock: formData.stock,
            categoryId: formData.categoryId,
            detail: formData.detail || undefined,
            tags: formData.tags,
            status: formData.status,
            existingImages: formData.existingImages
          };
          
          // 添加新上传的图片文件
          if (formData.imageFiles && formData.imageFiles.length > 0) {
            productData.images = formData.imageFiles;
          }
          
          // 调用API更新商品，传递商品ID，优先使用_id
          let result;
          try {
            // 使用API更新商品，优先使用_id
            result = await productStore.updateProductWithApi(formData._id || formData.id, productData);
            
            if (result.success) {
              // 显示成功提示
              showModal({
                title: '成功',
                message: result.message || '商品信息已更新',
                type: 'success'
              });
            } else {
              // 显示错误提示
              showModal({
                title: '错误',
                message: result.message || '更新商品失败',
                type: 'danger'
              });
            }
          } catch (error) {
            console.error('更新商品时发生错误:', error);
            // 显示错误提示
            showModal({
              title: '错误',
              message: error.message || '更新商品过程中发生错误',
              type: 'danger'
            });
          }
        }
      });
    }
    
    // 打开添加商品模态框
    function openAddModal() {
      showModal({
        title: '添加商品',
        type: 'info',
        showForm: true,
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '添加',
        formData: {
          id: '',
          name: '',
          price: '',
          originalPrice: '',
          stock: 100,
          categoryId: productStore.categories.length > 0 ? productStore.categories[0].id : '',
          image: '',
          imageFiles: [], // 用于存储上传的图片文件
          description: '',
          detail: '',
          tags: [],
          specs: [],
          status: '1'
        },
        callback: async (formData) => {
          // 显示loading
          showModal({
            title: '处理中',
            message: '正在上传商品数据，请稍候...',
            type: 'info'
          });
          
          // 准备提交的数据
          const productData = {
            name: formData.name,
            description: formData.description,
            price: formData.price,
            originalPrice: formData.originalPrice || undefined,
            stock: formData.stock,
            categoryId: formData.categoryId,
            detail: formData.detail || undefined,
            tags: formData.tags,
            status: formData.status
          };
          
          // 添加图片文件
          if (formData.imageFiles && formData.imageFiles.length > 0) {
            productData.images = formData.imageFiles;
          }
          
          // 调用API创建商品
          let result;
          try {
            // 检查新API函数是否存在
            if (typeof productStore.addNewProduct === 'function') {
              result = await productStore.addNewProduct(productData);
            } else {
              // 降级到旧的API函数
              const newProduct = productStore.addProduct(productData);
              result = {
                success: !!newProduct,
                product: newProduct,
                message: '商品已添加成功'
              };
            }
            
            if (result.success) {
              // 显示成功提示
              showModal({
                title: '成功',
                message: result.message || '商品已添加成功',
                type: 'success'
              });
            } else {
              // 显示错误提示
              showModal({
                title: '错误',
                message: result.message || '添加商品失败',
                type: 'danger'
              });
            }
          } catch (error) {
            console.error('添加商品时发生错误:', error);
            // 显示错误提示
            showModal({
              title: '错误',
              message: error.message || '添加商品过程中发生错误',
              type: 'danger'
            });
          }
        }
      });
    }
    
    // 显示模态框
    function showModal(options) {
      modal.show = true;
      modal.title = options.title || '提示';
      modal.message = options.message || '';
      modal.type = options.type || 'info';
      modal.showCancelButton = options.showCancelButton || false;
      modal.cancelButtonText = options.cancelButtonText || '取消';
      modal.confirmButtonText = options.confirmButtonText || '确定';
      modal.showForm = options.showForm || false;
      
      if (options.showForm && options.formData) {
        for (const key in options.formData) {
          if (Object.prototype.hasOwnProperty.call(modal.formData, key)) {
            modal.formData[key] = options.formData[key];
          }
        }
      }
      
      modal.callback = options.callback || (() => {});
    }
    
    // 确认操作
    function confirmModal() {
      if (modal.showForm) {
        // 如果是表单模式，将表单数据传递给回调函数
        // 表单验证
        if (!modal.formData.name || !modal.formData.price || !modal.formData.stock || !modal.formData.description) {
          // 显示错误提示
          showModal({
            title: '错误',
            message: '请填写完整商品信息（名称、价格、库存、描述为必填项）',
            type: 'danger'
          });
          return;
        }
        
        // 执行回调函数
        modal.callback(modal.formData);
      } else {
        // 普通模式，直接执行回调
        modal.callback();
      }
      
      // 关闭模态框
      closeModal();
    }
    
    // 关闭模态框
    function closeModal() {
      modal.show = false;
      
      // 重置表单数据
      if (modal.showForm) {
        setTimeout(() => {
          Object.keys(modal.formData).forEach(key => {
            if (key === 'stock') {
              modal.formData[key] = 0;
            } else if (key === 'status') {
              modal.formData[key] = '1';
            } else if (key === 'imageFiles') {
              modal.formData[key] = [];
            } else if (key === 'tags') {
              modal.formData[key] = [];
            } else if (key === 'specs') {
              modal.formData[key] = [];
            } else {
              modal.formData[key] = '';
            }
          });
          
          // 清空预览图片
          if (previewImages && previewImages.value) {
            previewImages.value = [];
          }
          
          // 清空标签输入
          if (tagInput) {
            tagInput.value = '';
          }
        }, 300);
      }
    }

    // 退出登录
    function logout() {
      userStore.logout();
      router.push('/login');
    }
    
    // 刷新商品列表
    function refreshProducts() {
      productStore.fetchProducts();
      // 显示刷新提示
      showModal({
        title: '刷新成功',
        message: '商品列表已刷新',
        type: 'success'
      });
    }
    
    // 清除搜索关键词
    function clearSearch() {
      productStore.exitSearchMode();
    }
    
    // 添加图片处理相关变量和方法
    const previewImages = ref([]);
    const tagInput = ref('');

    // 处理图片上传
    function handleImageUpload(event) {
      const files = event.target.files;
      if (!files || files.length === 0) return;
      
      // 初始化图片文件数组（如果不存在）
      if (!modal.formData.imageFiles) {
        modal.formData.imageFiles = [];
      }
      
      // 初始化预览图片数组（如果不存在）
      if (!previewImages.value) {
        previewImages.value = [];
      }
      
      // 检查文件是否是图片，并且大小合适
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
          showModal({
            title: '错误',
            message: `文件 "${file.name}" 不是有效的图片格式`,
            type: 'danger'
          });
          continue;
        }
        
        // 验证文件大小（2MB以内）
        if (file.size > 2 * 1024 * 1024) {
          showModal({
            title: '错误',
            message: `文件 "${file.name}" 超过2MB大小限制`,
            type: 'danger'
          });
          continue;
        }
        
        // 添加文件到上传列表
        modal.formData.imageFiles.push(file);
        
        // 创建预览URL
        const reader = new FileReader();
        reader.onload = e => {
          previewImages.value.push(e.target.result);
        };
        reader.readAsDataURL(file);
      }
      
      // 清除input的值，允许重复选择相同文件
      event.target.value = '';
    }

    // 移除图片
    function removeImage(index) {
      const totalImages = (modal.formData.existingImages ? modal.formData.existingImages.length : 0) + 
                          (modal.formData.imageFiles ? modal.formData.imageFiles.length : 0);
      
      // 如果只有一张图片，显示警告
      if (totalImages <= 1) {
        showModal({
          title: '警告',
          message: '商品至少需要一张图片',
          type: 'warning'
        });
        return;
      }
      
      // 判断是移除现有图片还是新上传的图片
      const existingImagesLength = modal.formData.existingImages ? modal.formData.existingImages.length : 0;
      
      if (index < existingImagesLength) {
        // 移除现有图片
        modal.formData.existingImages.splice(index, 1);
      } else {
        // 移除新上传的图片，需要调整索引
        const newIndex = index - existingImagesLength;
        modal.formData.imageFiles.splice(newIndex, 1);
      }
      
      // 移除预览图片
      previewImages.value.splice(index, 1);
    }

    // 添加标签
    function addTag() {
      if (!tagInput.value.trim()) return;
      
      // 检查是否已存在相同标签
      if (!modal.formData.tags.includes(tagInput.value.trim())) {
        modal.formData.tags.push(tagInput.value.trim());
      }
      
      // 清空输入框
      tagInput.value = '';
    }

    // 移除标签
    function removeTag(index) {
      modal.formData.tags.splice(index, 1);
    }

    return {
      productStore,
      topLevelCategories,
      subCategories,
      organizedCategories,
      getChildCategories,
      getParentCategoryName,
      isSidebarOpen,
      selectAll,
      modal,
      paginationNumbers,
      getModalHeaderClass,
      getModalConfirmButtonClass,
      toggleSelectAll,
      toggleSidebar,
      toggleStatus,
      deleteProduct,
      editProduct,
      openAddModal,
      batchUpdateStatus,
      batchDelete,
      showModal,
      closeModal,
      confirmModal,
      logout,
      goToPage,
      toggleSort,
      refreshProducts,
      getImageUrl,
      clearSearch,
      previewImages,
      tagInput,
      handleImageUpload,
      removeImage,
      addTag,
      removeTag
    };
  }
};
</script>

<style scoped>
[v-cloak] { display: none; }
/* 确保图标正确显示 */
.bi {
  display: inline-block;
  vertical-align: -0.125em;
}

/* 搜索框图标样式 */
.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
  z-index: 1;
}

/* 搜索框内边距调整 */
.search-input {
  padding-left: 36px !important;
}

/* 模态对话框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 50;
}

.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

.modal-content {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  transform: scale(1);
  transition: transform 0.3s ease;
}

.modal-enter-from .modal-content,
.modal-leave-to .modal-content {
  transform: scale(0.9);
}
</style>